package com.transsion.clouddemo.core.ulo.other

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.transsion.cloud_client_sdk.CloudSDKManager
import com.transsion.cloud_upload_sdk.utils.Utils
import com.transsion.clouddemo.CloudApplication
import com.transsion.clouddemo.R
import com.transsion.clouddemo.core.Custom.BaseInfoAdapter
import com.transsion.clouddemo.core.Custom.CloudClickListener
import com.transsion.clouddemo.core.Custom.utils.ToastUtils
import com.transsion.clouddemo.core.DataGenerator
import com.transsion.clouddemo.core.ulo.down.DownFragment
import com.transsion.clouddemo.core.ulo.down.DownMessageItem
import com.transsion.clouddemo.databinding.CloudOtherBinding
import java.io.File

class OtherFragment :Fragment(),Handler.Callback{

    private lateinit var mBinding: CloudOtherBinding

    private val mHandler = Handler(Looper.getMainLooper(), this)

    private val mRemoveDataList by lazy {DataGenerator.removeData}

    private val removeAdapter by lazy { BaseInfoAdapter(mRemoveDataList) }




    companion object {

        const val TAG="zhangxin"

        const val SUCCESS = "remove_success"
        const val FAIL = "remove_fail"
        const val LOGIN="login"

        const val REMOVE = 1000
        const val REMOVE_PERMANENT=1001
        const val ACQUIRE_NO_SYNC = 1002
        const val ACQUIRE_LOGIN = 1003


        // 定义自定义CSS来调整代码块的显示
        val customCss = """
    <style>
        pre {
            white-space: pre-wrap; /* 允许换行 */
            word-wrap: break-word; /* 自动换行 */
            overflow-x: auto; /* 横向滚动 */
        }
        code {
             ont-size: 10px; /* 设置字体大小 */
            white-space: pre-wrap; /* 允许换行 */
        }
    </style>
""".trimIndent()


        fun newInstance(): OtherFragment {
            return OtherFragment()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        mBinding = CloudOtherBinding.inflate(inflater, container, false)


        //初始化并发上传按钮
        initConcurrent()
        //初始化自定义线程池按钮
        initThreadPool()
        //初始化删除文件按钮
        initRemoveFile()
        //初始化获取未同步数据按钮
        initNoSync()
        //初始化获取账号登录状态按钮
        initCheckLogin()







        return mBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun handleMessage(msg: Message): Boolean {




        when (msg.what) {
            REMOVE->{
                val item=DownMessageItem(msg.data.getString(SUCCESS)!!,msg.data.getString(FAIL)!!)
                mRemoveDataList.add(item)
                removeAdapter.notifyDataSetChanged()
                mBinding.removeFileRecyclerView.scrollToPosition(mRemoveDataList.size - 1)
            }
            REMOVE_PERMANENT->{
                val item=DownMessageItem(msg.data.getString(SUCCESS)!!,msg.data.getString(FAIL)!!)
                mRemoveDataList.add(item)
                removeAdapter.notifyDataSetChanged()
                mBinding.removeFileRecyclerView.scrollToPosition(mRemoveDataList.size - 1)
            }
            ACQUIRE_NO_SYNC->{
                mBinding.acquireNoSync.apply {
                    isEnabled=true
                    text = getString(R.string.cloud_other_four_button)
                    setTextColor(context.getColor(R.color.cloud_text_default))
                    ToastUtils.showShort(requireContext(), "当前未同步数量 ${msg.data.getString(SUCCESS)}")
                }
            }
            ACQUIRE_LOGIN->{
                mBinding.acquireLogin.apply {
                    isEnabled=true
                    text = getString(R.string.cloud_other_four_button)
                    setTextColor(context.getColor(R.color.cloud_text_default))
                    ToastUtils.showShort(requireContext(), msg.data.getString(LOGIN)!!)
                }
            }
        }
        return true
    }

    fun initConcurrent() {

        mBinding.settingConcurrence.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.settingConcurrence.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_one_setting)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                CloudApplication.initCloudSdk(useConcurrent = true)
                mHandler.postDelayed({
                    mBinding.settingConcurrence.apply {
                        isEnabled=true
                        text = getString(R.string.cloud_other_one_button)
                        setTextColor(context.getColor(R.color.cloud_text_default))
                    }
                    ToastUtils.showShort(context!!, "设置成功")
                },1000)
            }
        })

        //代码提示区
        val markdownContent="```kotlin\n" +
                "CloudApplication.initCloudSdk(useConcurrent = true)" +
                "```".trimIndent()

        mBinding.markdownViewConcurrent.setMarkDownText( "${customCss}\n$markdownContent") // 使用setMarkDownText设置Markdown内容
    }

    fun initThreadPool() {

        mBinding.settingThreadPool.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.settingThreadPool.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_one_setting)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                CloudApplication.initCloudSdk(threadPool = true)
                mHandler.postDelayed({
                    mBinding.settingThreadPool.apply {
                        isEnabled=true
                        text = getString(R.string.cloud_other_one_button)
                        setTextColor(context.getColor(R.color.cloud_text_default))
                    }
                    ToastUtils.showShort(context!!, "设置成功")

                },1000)
            }
        })

        //代码提示区
        val markdownContent="```kotlin\n" +
                "CloudApplication.initCloudSdk(threadPool = true)" +
                "```".trimIndent()

        mBinding.markdownViewThreadpool.setMarkDownText( "${customCss}\n$markdownContent") // 使用setMarkDownText设置Markdown内容
    }

    fun initRemoveFile() {

        //初始化RecyclerView
        initRecyclerView()

        //本地删除
        mBinding.removeLocal.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.removeLocal.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_there_removing)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                CloudSDKManager.getInstance()
                    .removeFile(DataGenerator.listAllFilesInDirectory(Utils.sdkDirectory())) { key, info, response ->
                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")

                        var isSuccess = false
                        if (info.success()) {
                            isSuccess=true
                            //其实回调都是在主线程可以不用handler的
                            //本地删除文件
                            File(Utils.sdkDirectory()).listFiles()?.forEach { file ->
                                if (file.isFile) { // 检查是否是文件（而不是目录）
                                    val bundle = Bundle()
                                    val message = mHandler.obtainMessage(REMOVE)
                                    bundle.putString(SUCCESS, file.name)
                                    bundle.putString(FAIL, DataGenerator.codeToReason[info.code])
                                    val deleted = file.delete() // 尝试删除文件
                                    if (!deleted) {
                                        bundle.putString(FAIL, "本地删除文件失败")
                                    } else {
                                        mRemoveDataList[0].fail = ""
                                        mRemoveDataList[1].fail = ""
                                    }
                                    message.data = bundle
                                    mHandler.sendMessage(message)
                                }
                            }
                        }
                        if (!isSuccess) {
                            val bundle1 = Bundle().apply {
                                putString(SUCCESS, key)
                                putString(FAIL, DataGenerator.codeToReason[info.code])
                            }
                            val message1 = mHandler.obtainMessage(REMOVE)
                            message1.data = bundle1
                            mHandler.sendMessage(message1)
                        }
                        mBinding.removeLocal.apply {
                            isEnabled=true
                            text = resources.getString(R.string.cloud_other_there_button)
                            setTextColor(context.getColor(R.color.cloud_text_default))
                        }

                    }
            }

        })



        //永久删除
        mBinding.removePermanent.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.removePermanent.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_there_removing)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }

                CloudSDKManager.getInstance()
                        .removeFile(true,DataGenerator.listAllFilesInDirectory(Utils.sdkDirectory())) { key, info, response ->

                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")


                        var isSuccess = false
                        if (info.success()) {
                            isSuccess=true
                            //其实回调都是在主线程可以不用handler的
                            //本地删除文件
                            File(Utils.sdkDirectory()).listFiles()?.forEach { file ->
                                if (file.isFile) { // 检查是否是文件（而不是目录）
                                    val bundle = Bundle()
                                    val message = mHandler.obtainMessage(REMOVE_PERMANENT)
                                    bundle.putString(SUCCESS, file.name)
                                    bundle.putString(
                                        FAIL,
                                        DataGenerator.codeToReason[info.code]
                                    )
                                    val deleted = file.delete() // 尝试删除文件
                                    Log.e("zhangxin", "删除文件成功")
                                    if (!deleted) {
                                        bundle.putString(FAIL, "本地删除文件失败")
                                    }else {
                                        mRemoveDataList[0].fail = ""
                                        mRemoveDataList[1].fail = ""
                                    }
                                    message.data = bundle
                                    mHandler.sendMessage(message)
                                }
                            }
                        }
                        if (!isSuccess) {
                            val message1 = mHandler.obtainMessage(REMOVE_PERMANENT)
                            val bundle1 = Bundle().apply {
                                putString(SUCCESS, key)
                                putString(FAIL, DataGenerator.codeToReason[info.code])
                            }
                            message1.data = bundle1
                            mHandler.sendMessage(message1)
                        }
                        mBinding.removePermanent.apply {
                            isEnabled=true
                            text = resources.getString(R.string.cloud_other_there_button_permanent)
                            setTextColor(context.getColor(R.color.cloud_text_default))
                        }
                    }
                }

        })

        //清除
        mBinding.clear.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (mRemoveDataList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(DownFragment.TAG,"开始删除数据=================")
                    mRemoveDataList.subList(2, mRemoveDataList.size).clear()
                    mRemoveDataList[0].fail = "下载失败!"
                    mRemoveDataList[1].fail = "失败原因："
                    removeAdapter.notifyDataSetChanged()
                }
            }
        })

    }



    fun initRecyclerView() {
        mBinding.removeFileRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter=removeAdapter

        }
    }

    fun initNoSync() {
        mBinding.acquireNoSync.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.acquireNoSync.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_four_acquiring)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                CloudSDKManager.getInstance()
                    .getNoSyncCount(CloudApplication.currentScene) { key, info, response ->
                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")

                        val message = mHandler.obtainMessage(ACQUIRE_NO_SYNC)
                        val bundle = Bundle().apply {
                            putString(SUCCESS, response)
                            putString(FAIL, DataGenerator.codeToReason[info.code])
                        }
                        message.data = bundle
                        mHandler.sendMessage(message)
                    }
            }

        })

        //代码提示区
        mBinding.markdownViewNoSyncInfo.setMarkDownText("${customCss}\n"+"直接调用以下方法即可：\n"+
                "```kotlin \n" +
                "CloudSDKManager.getInstance().getNoSyncCount(CloudApplication.currentScene) {}\n" +
                "```\n" +
                "- 它也是根据scene和operateVersion来决定没有同步的数量")


    }

    fun initCheckLogin() {

        mBinding.acquireLogin.setOnClickListener(object :CloudClickListener(){
            override fun onSingleClick(view: View) {

                mBinding.acquireLogin.apply {
                    isEnabled=false
                    text = getString(R.string.cloud_other_four_acquiring)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                val checkLogin = CloudSDKManager.getInstance().checkLogin()
                val message = mHandler.obtainMessage(ACQUIRE_LOGIN)
                message.data = Bundle().apply { putString(LOGIN, checkLogin.toString()) }
                mHandler.sendMessage(message)
            }


        })

        //代码提示区
        mBinding.markdownViewCheckLogin.setMarkDownText("${customCss}\n通过以下方法查看：\n" +
                "```kotlin\n" +"val checkLogin = CloudSDKManager.getInstance().checkLogin()" +
                "```\n"+
                "```java\n" +
                "public boolean checkLogin() {\n" +
                "    return !TextUtils.isEmpty(UtilsSdkInit.INSTANCE.getAccessToken());\n" +
                "}\n" +
                "```")

    }

    fun deleteFilesInDirectory() {
        // 获取指定目录的文件列表
        val files: Array<File>? = File(Utils.sdkDirectory()).listFiles() // 获取指定目录的文件数组

        // 遍历文件数组
        files?.forEach { file ->
            if (file.isFile) { // 检查是否是文件（而不是目录）
                val deleted = file.delete() // 尝试删除文件
                if (deleted) {
                    println("Deleted: ${file.name}") // 打印已删除文件的名称
                } else {
                    println("Failed to delete: ${file.name}") // 打印删除失败的文件名称
                }
            }
        }
    }


}